// 页面加载完成后执行初始化
document.addEventListener('DOMContentLoaded', function() {
    // 初始化表单时间
    const now = new Date();
    const nowString = formatDateForInput(now);
    
    document.getElementById('feedingTime').value = nowString;
    document.getElementById('eventDate').value = now.toISOString().split('T')[0];
    
    // 加载配置
    loadConfig();
    
    // 加载数据
    loadFeedingRecords();
    loadEvents();
    updateNextFeedingTime();
    
    // 设置定时器定期更新下次喂养时间
    setInterval(updateNextFeedingTime, 60000); // 每分钟更新一次
    
    // 绑定事件监听器
    document.getElementById('feedingForm').addEventListener('submit', handleFeedingSubmit);
    document.getElementById('eventForm').addEventListener('submit', handleEventSubmit);
    document.getElementById('quickRecordBtn').addEventListener('click', quickRecordFeeding);
    document.getElementById('refreshFeedingBtn').addEventListener('click', updateNextFeedingTime);
    document.getElementById('configForm').addEventListener('submit', handleConfigSubmit);
    document.getElementById('fetchGoldPricesBtn').addEventListener('click', fetchGoldPrices);
    
    // 绑定筛选器事件监听器
    document.getElementById('feedingHoursFilter').addEventListener('change', loadFeedingRecords);
    document.getElementById('eventsDaysFilter').addEventListener('change', loadEvents);
    
    // Tab切换
    const tabButtons = document.querySelectorAll('.tab-button');
    tabButtons.forEach(button => {
        button.addEventListener('click', () => {
            // 移除所有活动状态
            tabButtons.forEach(btn => btn.classList.remove('active'));
            document.querySelectorAll('.tab-content').forEach(content => content.classList.remove('active'));
            
            // 添加活动状态到当前按钮和对应内容
            button.classList.add('active');
            const tabId = button.getAttribute('data-tab');
            document.getElementById(`${tabId}-tab`).classList.add('active');
            
            // 如果切换到行情查询tab，则自动获取黄金价格
            if (tabId === 'market') {
                fetchGoldPrices();
            }
        });
    });
});

// 格式化日期用于datetime-local输入框
function formatDateForInput(date) {
    const year = date.getFullYear();
    const month = String(date.getMonth() + 1).padStart(2, '0');
    const day = String(date.getDate()).padStart(2, '0');
    const hours = String(date.getHours()).padStart(2, '0');
    const minutes = String(date.getMinutes()).padStart(2, '0');
    
    return `${year}-${month}-${day}T${hours}:${minutes}`;
}

// 加载配置
function loadConfig() {
    fetch('/api/config')
    .then(response => response.json())
    .then(config => {
        document.getElementById('feedingInterval').value = config.feeding_interval_hours || 3.5;
        document.getElementById('defaultFeedingType').value = config.default_feeding_type || '瓶喂';
        document.getElementById('defaultFeedingAmount').value = config.default_feeding_amount || '120ml';
        
        // 设置当前表单的默认值
        document.getElementById('feedingType').value = config.default_feeding_type || '瓶喂';
        document.getElementById('feedingAmount').value = config.default_feeding_amount || '120ml';
        
        // 更新版本号显示
        document.getElementById('versionInfo').textContent = '版本号：' + (config.version || 'V1.0.0');
    })
    .catch(error => {
        console.error('Error loading config:', error);
    });
}

// 处理配置提交
function handleConfigSubmit(e) {
    e.preventDefault();
    
    const configData = {
        feeding_interval_hours: parseFloat(document.getElementById('feedingInterval').value),
        default_feeding_type: document.getElementById('defaultFeedingType').value,
        default_feeding_amount: document.getElementById('defaultFeedingAmount').value
    };
    
    fetch('/api/config', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
        },
        body: JSON.stringify(configData)
    })
    .then(response => response.json())
    .then(data => {
        if (data.status === 'success') {
            alert('配置已保存！');
            // 更新当前表单的默认值
            document.getElementById('feedingType').value = configData.default_feeding_type;
            document.getElementById('feedingAmount').value = configData.default_feeding_amount;
        } else {
            alert('保存失败，请重试');
        }
    })
    .catch(error => {
        console.error('Error:', error);
        alert('发生错误，请重试');
    });
}

// 处理喂养记录提交
function handleFeedingSubmit(e) {
    e.preventDefault();
    
    const feedingData = {
        time: document.getElementById('feedingTime').value.replace('T', ' '),
        type: document.getElementById('feedingType').value,
        amount: document.getElementById('feedingAmount').value,
        note: document.getElementById('feedingNote').value  // 添加备注字段
    };
    
    fetch('/api/feeding', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
        },
        body: JSON.stringify(feedingData)
    })
    .then(response => response.json())
    .then(data => {
        if (data.status === 'success') {
            alert('喂养记录已保存！');
            loadFeedingRecords();
            updateNextFeedingTime();
            // 重置表单
            document.getElementById('feedingForm').reset();
            const now = new Date();
            document.getElementById('feedingTime').value = formatDateForInput(now);
            
            // 重新加载配置以获取默认值
            loadConfig();
        } else {
            alert('保存失败，请重试');
        }
    })
    .catch(error => {
        console.error('Error:', error);
        alert('发生错误，请重试');
    });
}

// 快速记录当前喂养
function quickRecordFeeding() {
    // 获取当前配置的默认值
    const defaultType = document.getElementById('defaultFeedingType').value || '瓶喂';
    const defaultAmount = document.getElementById('defaultFeedingAmount').value || '120ml';
    
    const now = new Date();
    const feedingData = {
        time: formatDateForInput(now).replace('T', ' '),
        type: defaultType,
        amount: defaultAmount
    };
    
    fetch('/api/feeding', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
        },
        body: JSON.stringify(feedingData)
    })
    .then(response => response.json())
    .then(data => {
        if (data.status === 'success') {
            alert('已快速记录当前喂养时间！');
            loadFeedingRecords();
            updateNextFeedingTime();
        } else {
            alert('保存失败，请重试');
        }
    })
    .catch(error => {
        console.error('Error:', error);
        alert('发生错误，请重试');
    });
}

// 处理事件提交
function handleEventSubmit(e) {
    e.preventDefault();
    
    const eventData = {
        date: document.getElementById('eventDate').value,
        content: document.getElementById('eventContent').value,
        category: document.getElementById('eventCategory').value
    };
    
    fetch('/api/events', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
        },
        body: JSON.stringify(eventData)
    })
    .then(response => response.json())
    .then(data => {
        if (data.status === 'success') {
            alert('事件已保存！');
            loadEvents();
            // 重置表单
            document.getElementById('eventForm').reset();
            const now = new Date();
            document.getElementById('eventDate').value = now.toISOString().split('T')[0];
        } else {
            alert('保存失败，请重试');
        }
    })
    .catch(error => {
        console.error('Error:', error);
        alert('发生错误，请重试');
    });
}

// 加载喂养记录
function loadFeedingRecords() {
    const hours = document.getElementById('feedingHoursFilter').value;
    let url = '/api/feeding';
    if (hours !== undefined) {
        url += `?hours=${hours}`;
    }
    
    fetch(url)
    .then(response => response.json())
    .then(records => {
        const container = document.getElementById('feedingRecordsList');
        
        // 按时间倒序排列
        records.sort((a, b) => new Date(b.time) - new Date(a.time));
        
        if (records.length === 0) {
            container.innerHTML = '<li>暂无喂养记录</li>';
            return;
        }
        
        container.innerHTML = records.map(record => {
            // 兼容旧版本数据，如果没有note字段则设为空字符串
            const note = record.note || '';
            const noteDisplay = note ? `<div class="record-note">备注: ${note}</div>` : '';
            
            return `
            <li class="feeding-record" data-id="${record.id}">
                <div class="record-details">
                    <div class="record-time">${record.time}</div>
                    <div class="record-type">${record.type}</div>
                    <div class="record-amount">${record.amount || '未指定分量'}</div>
                    ${noteDisplay}
                </div>
                <div class="record-actions">
                    <button class="edit-btn" onclick="editFeedingRecord('${record.id}')">编辑</button>
                    <button class="delete-btn" onclick="deleteFeedingRecord('${record.id}')">删除</button>
                </div>
            </li>
        `}).join('');
    })
    .catch(error => {
        console.error('Error:', error);
    });
}

// 编辑喂养记录
function editFeedingRecord(recordId) {
    // 获取当前记录数据
    fetch('/api/feeding')
    .then(response => response.json())
    .then(records => {
        const record = records.find(r => r.id === recordId);
        if (!record) return;
        
        // 兼容旧版本数据，如果没有note字段则设为空字符串
        const note = record.note || '';
        
        // 创建编辑表单
        const recordElement = document.querySelector(`.feeding-record[data-id="${recordId}"]`);
        const editForm = document.createElement('div');
        editForm.className = 'edit-form';
        editForm.innerHTML = `
            <h4>编辑喂养记录</h4>
            <div class="form-group">
                <label>喂养时间:</label>
                <input type="datetime-local" id="editFeedingTime" value="${record.time.replace(' ', 'T')}">
            </div>
            <div class="form-group">
                <label>喂养类型:</label>
                <select id="editFeedingType">
                    <option value="亲喂" ${record.type === '亲喂' ? 'selected' : ''}>亲喂</option>
                    <option value="瓶喂" ${record.type === '瓶喂' ? 'selected' : ''}>瓶喂</option>
                    <option value="奶粉" ${record.type === '奶粉' ? 'selected' : ''}>奶粉</option>
                    <option value="辅食" ${record.type === '辅食' ? 'selected' : ''}>辅食</option>
                    <option value="AD" ${record.type === 'AD' ? 'selected' : ''}>AD</option>
                    <option value="益生菌" ${record.type === '益生菌' ? 'selected' : ''}>益生菌</option>
                    <option value="水" ${record.type === '水' ? 'selected' : ''}>水</option>
                    <option value="零食" ${record.type === '零食' ? 'selected' : ''}>零食</option>
                </select>
            </div>
            <div class="form-group">
                <label>分量:</label>
                <input type="text" id="editFeedingAmount" value="${record.amount}">
            </div>
            <div class="form-group">
                <label>备注:</label>
                <input type="text" id="editFeedingNote" value="${note}">
            </div>
            <button class="btn-secondary" onclick="saveFeedingRecord('${recordId}')">保存</button>
            <button class="btn-refresh" onclick="cancelEdit(this)">取消</button>
        `;
        
        recordElement.appendChild(editForm);
    });
}

// 保存喂养记录修改
function saveFeedingRecord(recordId) {
    const updatedData = {
        time: document.getElementById('editFeedingTime').value.replace('T', ' '),
        type: document.getElementById('editFeedingType').value,
        amount: document.getElementById('editFeedingAmount').value,
        note: document.getElementById('editFeedingNote').value  // 添加备注字段
    };
    
    fetch(`/api/feeding/${recordId}`, {
        method: 'PUT',
        headers: {
            'Content-Type': 'application/json',
        },
        body: JSON.stringify(updatedData)
    })
    .then(response => response.json())
    .then(data => {
        if (data.status === 'success') {
            alert('记录已更新！');
            loadFeedingRecords();
            updateNextFeedingTime();
        } else {
            alert('更新失败，请重试');
        }
    })
    .catch(error => {
        console.error('Error:', error);
        alert('发生错误，请重试');
    });
}

// 删除喂养记录
function deleteFeedingRecord(recordId) {
    if (!confirm('确定要删除这条喂养记录吗？')) {
        return;
    }
    
    fetch(`/api/feeding/${recordId}`, {
        method: 'DELETE'
    })
    .then(response => response.json())
    .then(data => {
        if (data.status === 'success') {
            alert('记录已删除！');
            loadFeedingRecords();
            updateNextFeedingTime();
        } else {
            alert('删除失败，请重试');
        }
    })
    .catch(error => {
        console.error('Error:', error);
        alert('发生错误，请重试');
    });
}

// 加载事件
function loadEvents() {
    const days = document.getElementById('eventsDaysFilter').value;
    let url = '/api/events';
    if (days !== undefined) {
        url += `?days=${days}`;
    }
    
    fetch(url)
    .then(response => response.json())
    .then(events => {
        const container = document.getElementById('eventsTimeline');
        
        // 按日期倒序排列
        events.sort((a, b) => new Date(b.date) - new Date(a.date));
        
        if (events.length === 0) {
            container.innerHTML = '<li>暂无成长事件</li>';
            return;
        }
        
        container.innerHTML = events.map(event => `
            <li class="event-item" data-id="${event.id}">
                <div class="event-details">
                    <div class="event-date">${event.date}</div>
                    <div class="event-content">${event.content}</div>
                    <div class="event-category">${getCategoryText(event.category)}</div>
                </div>
                <div class="event-actions">
                    <button class="edit-btn" onclick="editEvent('${event.id}')">编辑</button>
                    <button class="delete-btn" onclick="deleteEvent('${event.id}')">删除</button>
                </div>
            </li>
        `).join('');
    })
    .catch(error => {
        console.error('Error:', error);
    });
}

// 编辑事件
function editEvent(eventId) {
    // 获取当前事件数据
    fetch('/api/events')
    .then(response => response.json())
    .then(events => {
        const event = events.find(e => e.id === eventId);
        if (!event) return;
        
        // 创建编辑表单
        const eventElement = document.querySelector(`.event-item[data-id="${eventId}"]`);
        const editForm = document.createElement('div');
        editForm.className = 'edit-form';
        editForm.innerHTML = `
            <h4>编辑事件</h4>
            <div class="form-group">
                <label>事件日期:</label>
                <input type="date" id="editEventDate" value="${event.date}">
            </div>
            <div class="form-group">
                <label>事件内容:</label>
                <textarea id="editEventContent">${event.content}</textarea>
            </div>
            <div class="form-group">
                <label>事件类型:</label>
                <select id="editEventCategory">
                    <option value="health" ${event.category === 'health' ? 'selected' : ''}>健康</option>
                    <option value="development" ${event.category === 'development' ? 'selected' : ''}>发育</option>
                    <option value="fun" ${event.category === 'fun' ? 'selected' : ''}>趣事</option>
                    <option value="family" ${event.category === 'family' ? 'selected' : ''}>家庭</option>
                    <option value="activity" ${event.category === 'activity' ? 'selected' : ''}>活动</option>
                    <option value="general" ${event.category === 'general' ? 'selected' : ''}>其他</option>
                </select>
            </div>
            <button class="btn-primary" onclick="saveEvent('${eventId}')">保存</button>
            <button class="btn-refresh" onclick="cancelEdit(this)">取消</button>
        `;
        
        eventElement.appendChild(editForm);
    });
}

// 保存事件修改
function saveEvent(eventId) {
    const updatedData = {
        date: document.getElementById('editEventDate').value,
        content: document.getElementById('editEventContent').value,
        category: document.getElementById('editEventCategory').value
    };
    
    fetch(`/api/events/${eventId}`, {
        method: 'PUT',
        headers: {
            'Content-Type': 'application/json',
        },
        body: JSON.stringify(updatedData)
    })
    .then(response => response.json())
    .then(data => {
        if (data.status === 'success') {
            alert('事件已更新！');
            loadEvents();
        } else {
            alert('更新失败，请重试');
        }
    })
    .catch(error => {
        console.error('Error:', error);
        alert('发生错误，请重试');
    });
}

// 删除事件
function deleteEvent(eventId) {
    if (!confirm('确定要删除这条事件吗？')) {
        return;
    }
    
    fetch(`/api/events/${eventId}`, {
        method: 'DELETE'
    })
    .then(response => response.json())
    .then(data => {
        if (data.status === 'success') {
            alert('事件已删除！');
            loadEvents();
        } else {
            alert('删除失败，请重试');
        }
    })
    .catch(error => {
        console.error('Error:', error);
        alert('发生错误，请重试');
    });
}

// 取消编辑
function cancelEdit(button) {
    const editForm = button.closest('.edit-form');
    if (editForm) {
        editForm.remove();
    }
}

// 更新下次喂养时间
function updateNextFeedingTime() {
    fetch('/api/feeding/next')
    .then(response => response.json())
    .then(data => {
        const timeElement = document.getElementById('nextFeedingTime');
        const messageElement = document.getElementById('feedingMessage');
        
        if (data.status === 'no_data') {
            timeElement.textContent = '暂无喂养记录';
            messageElement.textContent = '请先记录一次喂养';
            messageElement.className = '';
            return;
        }
        
        if (data.status === 'no_feeding_data') {
            timeElement.textContent = '暂无有效喂养记录';
            messageElement.textContent = '请先记录一次瓶喂、亲喂或奶粉喂养';
            messageElement.className = '';
            return;
        }
        
        timeElement.textContent = data.next_feeding;
        
        if (data.due) {
            messageElement.textContent = '该喂养啦！';
            messageElement.className = 'due';
        } else {
            const hours = Math.floor(data.remaining_minutes / 60);
            const minutes = data.remaining_minutes % 60;
            messageElement.textContent = `还有 ${hours} 小时 ${minutes} 分钟`;
            messageElement.className = '';
        }
    })
    .catch(error => {
        console.error('Error:', error);
    });
}

// 获取喂养类型文本
function getFeedingTypeText(type) {
    return type;
}

// 获取事件分类文本
function getCategoryText(category) {
    const categories = {
        'health': '健康',
        'development': '发育',
        'fun': '趣事',
        'family': '家庭',
        'activity': '活动',
        'general': '其他'
    };
    return categories[category] || category;
}

// 获取黄金价格信息
function fetchGoldPrices() {
    const container = document.getElementById('goldPricesContainer');
    container.innerHTML = '<p>正在获取数据...</p>';
    
    fetch('/api/gold-prices')
    .then(response => {
        if (!response.ok) {
            throw new Error('网络响应异常');
        }
        return response.json();
    })
    .then(data => {
        if (data.error) {
            container.innerHTML = `<p style="color: red;">获取失败: ${data.error}</p>`;
            return;
        }
        
        let html = '';
        for (const [name, info] of Object.entries(data)) {
            html += `
                <div class="gold-price-item">
                    <h4>${name}</h4>
                    <p>当前价格: ${info['当前价格']}</p>
                    <p>昨结算价: ${info['昨结算价']}</p>
                    <p>涨跌幅度: ${info['涨幅']}</p>
                    <p>更新时间: ${info['更新时间']}</p>
                </div>
                <hr>
            `;
        }
        container.innerHTML = html || '<p>暂无数据</p>';
    })
    .catch(error => {
        console.error('Error:', error);
        container.innerHTML = `<p style="color: red;">获取失败: ${error.message}</p>`;
    });
}
